﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;

namespace CSConsoleTest
{
    class TestCOM : BaseConsoleTest
    {
        public void printDescription()
        {
            Console.WriteLine("--- COM (Component Object Model) ---");
        }

        public void doTest()
        {
            string savePath = "D:\\temp";
            string[,] contactsTable = new string[,] { 
                { "TestMan1", "010-1111-1111" }, 
                { "TestMan2", "010-2222-2222" },
                { "TestMan3", "010-3333-3333" },
                { "TestMan4", "010-4444-4444" },
                { "TestMan5", "010-5555-5555" },
            };
            comOldWay(contactsTable, savePath);
            comNewWay(contactsTable, savePath);
        }

        public static void comOldWay(string[,] data, string savePath)
        {
            Excel.Application excelApp = new Excel.Application();
            excelApp.Workbooks.Add(Type.Missing);
            Excel.Worksheet worksheet = (Excel.Worksheet)excelApp.ActiveSheet;

            for (int i = 0; i < data.GetLength(0); i++)
            {
                ((Excel.Range)worksheet.Cells[i + 1, 1]).Value2 = data[i, 0];
                ((Excel.Range)worksheet.Cells[i + 1, 2]).Value2 = data[i, 1];
            }

            FileInfo targetFile = new FileInfo(savePath + "\\com_old_test_excel.xlsx");
            if (targetFile.Exists)
            {
                targetFile.Delete();
            }

            worksheet.SaveAs(targetFile.FullName,
                Type.Missing,
                Type.Missing,
                Type.Missing,
                Type.Missing,
                Type.Missing,
                Type.Missing,
                Type.Missing,
                Type.Missing,
                Type.Missing);

            excelApp.Quit();
        }

        public static void comNewWay(string[,] data, string savePath)
        {
            Excel.Application excelApp = new Excel.Application();
            excelApp.Workbooks.Add();
            Excel._Worksheet worksheet = excelApp.ActiveSheet;

            for (int i = 0; i < data.GetLength(0); i++)
            {
                worksheet.Cells[i + 1, 1] = data[i, 0];
                worksheet.Cells[i + 1, 2] = data[i, 1];
            }

            FileInfo targetFile = new FileInfo(savePath + "\\com_new_test_excel.xlsx");
            if (targetFile.Exists)
            {
                targetFile.Delete();
            }

            worksheet.SaveAs(targetFile.FullName);

            excelApp.Quit();
        }
    }
}
